{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "initial_id",
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    ""
   ]
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 提示词模板之ChatPromptTemplate的使用\n",
    "\n",
    "1、实例化的方式（两种方式：使用构造方法、from_messages()）\n",
    "\n",
    "2、调用提示词模板的几种方法：invoke() \\ format() \\ format_messages() \\ format_prompt()\n",
    "\n",
    "3、更丰富的实例化参数类型\n",
    "\n",
    "4、结合LLM\n",
    "\n",
    "5、插入消息列表：MessagePlaceholder\n",
    "\n",
    "## 1、实例化的方式\n",
    "\n",
    "方式1：使用构造方法"
   ],
   "id": "123f8acd972fdc7a"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T17:31:34.039786Z",
     "start_time": "2025-09-28T17:31:33.355268Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder, HumanMessagePromptTemplate\n",
    "\n",
    "# 创建实例\n",
    "chat_prompt = ChatPromptTemplate(\n",
    "    messages=[\n",
    "        (\"system\", \"你是一个AI助手，你的名字叫{name}\"),\n",
    "        (\"human\", \"我的问题是{question}\")\n",
    "    ],\n",
    "    input_variables=[\"name\", \"question\"]\n",
    "\n",
    ")\n",
    "response = chat_prompt.invoke(input={\"name\": \"小智\", \"question\": \"1 + 2 * 3 = ？\"})\n",
    "\n",
    "print(response)\n",
    "print(type(response))  #<class 'langchain_core.prompt_values.ChatPromptValue'>\n",
    "print(len(response.messages))"
   ],
   "id": "359fdad2d2d18b76",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/opt/miniconda3/envs/pyth310/lib/python3.10/site-packages/requests/__init__.py:86: RequestsDependencyWarning: Unable to find acceptable character detection dependency (chardet or charset_normalizer).\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "messages=[SystemMessage(content='你是一个AI助手，你的名字叫小智', additional_kwargs={}, response_metadata={}), HumanMessage(content='我的问题是1 + 2 * 3 = ？', additional_kwargs={}, response_metadata={})]\n",
      "<class 'langchain_core.prompt_values.ChatPromptValue'>\n",
      "2\n"
     ]
    }
   ],
   "execution_count": 1
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "更简洁的方式：",
   "id": "b98e15e73be85da0"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T17:33:59.839644Z",
     "start_time": "2025-09-28T17:33:59.830279Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 创建实例\n",
    "chat_prompt_template = ChatPromptTemplate(\n",
    "    [\n",
    "        (\"system\", \"你是一个AI助手，你的名字叫{name}\"),\n",
    "        (\"human\", \"我的问题是{question}\")\n",
    "    ]\n",
    ")\n",
    "\n",
    "response = chat_prompt_template.invoke({\"name\": \"小智\", \"question\": \"1 + 2 * 3 = ？\"})\n",
    "print(response)\n",
    "print(type(response))  #<class 'langchain_core.prompt_values.ChatPromptValue'>\n",
    "print(len(response.messages))"
   ],
   "id": "56457d3001552c26",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "messages=[SystemMessage(content='你是一个AI助手，你的名字叫小智', additional_kwargs={}, response_metadata={}), HumanMessage(content='我的问题是1 + 2 * 3 = ？', additional_kwargs={}, response_metadata={})]\n",
      "<class 'langchain_core.prompt_values.ChatPromptValue'>\n",
      "2\n"
     ]
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "方式2：调用from_message()",
   "id": "9a7a064ac1b1e35b"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T17:35:49.180740Z",
     "start_time": "2025-09-28T17:35:49.172314Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "# chat_prompt_template = ChatPromptTemplate(\n",
    "#     [\n",
    "#         (\"system\",\"你是一个AI助手，你的名字叫{name}\"),\n",
    "#         (\"human\",\"我的问题是{question}\")\n",
    "#     ]\n",
    "# )\n",
    "\n",
    "chat_prompt_template = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\"system\", \"你是一个AI助手，你的名字叫{name}\"),\n",
    "        (\"human\", \"我的问题是{question}\")\n",
    "    ]\n",
    ")\n",
    "\n",
    "response = chat_prompt_template.invoke({\"name\": \"小智\", \"question\": \"1 + 2 * 3 = ？\"})\n",
    "print(response)\n",
    "print(type(response))  #<class 'langchain_core.prompt_values.ChatPromptValue'>\n",
    "print(len(response.messages))"
   ],
   "id": "fd032b3f34dbf328",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "messages=[SystemMessage(content='你是一个AI助手，你的名字叫小智', additional_kwargs={}, response_metadata={}), HumanMessage(content='我的问题是1 + 2 * 3 = ？', additional_kwargs={}, response_metadata={})]\n",
      "<class 'langchain_core.prompt_values.ChatPromptValue'>\n",
      "2\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## 2、调用提示词模板的几种方法\n",
    "\n",
    "invoke() \\ format() \\ format_messages() \\ format_prompt()\n",
    "\n",
    "invoke()：传入的是字典，返回ChatPromptValue\n",
    "\n",
    "format():传入变量的值，返回str\n",
    "\n",
    "format_messages(): 传入变量的值，返回消息构成的list\n",
    "\n",
    "format_prompt(): 传入变量的值，返回ChatPromptValue\n",
    "\n",
    "#举例1：invoke()"
   ],
   "id": "16622a8afae1842a"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T17:36:58.344095Z",
     "start_time": "2025-09-28T17:36:58.337185Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "\n",
    "# 创建实例\n",
    "\n",
    "chat_prompt_template = ChatPromptTemplate.from_messages([\n",
    "    (\"system\", \"你是一个AI助手，你的名字叫{name}\"),\n",
    "    (\"human\", \"我的问题是{question}\")\n",
    "])\n",
    "\n",
    "response = chat_prompt_template.invoke({\"name\": \"小智\", \"question\": \"1 + 2 * 3 = ？\"})\n",
    "print(response)\n",
    "print(type(response))  #<class 'langchain_core.prompt_values.ChatPromptValue'>"
   ],
   "id": "32f61784c236780b",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "messages=[SystemMessage(content='你是一个AI助手，你的名字叫小智', additional_kwargs={}, response_metadata={}), HumanMessage(content='我的问题是1 + 2 * 3 = ？', additional_kwargs={}, response_metadata={})]\n",
      "<class 'langchain_core.prompt_values.ChatPromptValue'>\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：format()",
   "id": "5c1413767021c57d"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T17:38:04.919069Z",
     "start_time": "2025-09-28T17:38:04.912220Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "\n",
    "# 创建实例\n",
    "\n",
    "chat_prompt_template = ChatPromptTemplate.from_messages([\n",
    "    (\"system\", \"你是一个AI助手，你的名字叫{name}\"),\n",
    "    (\"human\", \"我的问题是{question}\")\n",
    "])\n",
    "\n",
    "response = chat_prompt_template.format(name=\"小智\", question=\"1 + 2 * 3 = ？\")\n",
    "print(response)\n",
    "print(type(response))"
   ],
   "id": "dc573eee29bd7979",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "System: 你是一个AI助手，你的名字叫小智\n",
      "Human: 我的问题是1 + 2 * 3 = ？\n",
      "<class 'str'>\n"
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例3：format_messages()",
   "id": "53c6db52970ba5b3"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T17:40:07.233075Z",
     "start_time": "2025-09-28T17:40:07.226596Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "\n",
    "# 创建实例\n",
    "\n",
    "chat_prompt_template = ChatPromptTemplate.from_messages([\n",
    "    (\"system\", \"你是一个AI助手，你的名字叫{name}\"),\n",
    "    (\"human\", \"我的问题是{question}\")\n",
    "])\n",
    "\n",
    "response = chat_prompt_template.format_messages(name=\"小智\", question=\"1 + 2 * 3 = ？\")\n",
    "print(response)\n",
    "print(type(response))  #<class 'list'>"
   ],
   "id": "d7718a27e51d9206",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[SystemMessage(content='你是一个AI助手，你的名字叫小智', additional_kwargs={}, response_metadata={}), HumanMessage(content='我的问题是1 + 2 * 3 = ？', additional_kwargs={}, response_metadata={})]\n",
      "<class 'list'>\n"
     ]
    }
   ],
   "execution_count": 7
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例4：format_prompt()",
   "id": "24b1dc41fae0de66"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T17:40:47.053728Z",
     "start_time": "2025-09-28T17:40:47.045351Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "\n",
    "# 创建实例\n",
    "\n",
    "chat_prompt_template = ChatPromptTemplate.from_messages([\n",
    "    (\"system\", \"你是一个AI助手，你的名字叫{name}\"),\n",
    "    (\"human\", \"我的问题是{question}\")\n",
    "])\n",
    "\n",
    "response = chat_prompt_template.format_prompt(name=\"小智\", question=\"1 + 2 * 3 = ？\")\n",
    "print(response)\n",
    "print(type(response))  #<class 'langchain_core.prompt_values.ChatPromptValue'>"
   ],
   "id": "47f26827d3b29fba",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "messages=[SystemMessage(content='你是一个AI助手，你的名字叫小智', additional_kwargs={}, response_metadata={}), HumanMessage(content='我的问题是1 + 2 * 3 = ？', additional_kwargs={}, response_metadata={})]\n",
      "<class 'langchain_core.prompt_values.ChatPromptValue'>\n"
     ]
    }
   ],
   "execution_count": 8
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "如何实现ChatPromptValue与list[messages]、字符串之间的转换",
   "id": "cb5e7b2f4a9583c9"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T17:44:34.647869Z",
     "start_time": "2025-09-28T17:44:34.640419Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "\n",
    "# 创建实例\n",
    "\n",
    "chat_prompt_template = ChatPromptTemplate.from_messages([\n",
    "    (\"system\", \"你是一个AI助手，你的名字叫{name}\"),\n",
    "    (\"human\", \"我的问题是{question}\")\n",
    "])\n",
    "\n",
    "# response = chat_prompt_template.format_prompt(name=\"小智\", question=\"1 + 2 * 3 = ？\")\n",
    "response = chat_prompt_template.invoke({\"name\": \"小智\", \"question\": \"1 + 2 * 3 = ？\"})\n",
    "# 将ChatPromptValue类型转换为消息构成的list\n",
    "response_messages = response.to_messages()\n",
    "print(response_messages)\n",
    "print(type(response_messages))\n",
    "print(\"~\" * 50)\n",
    "# 将ChatPromptValue类型转换为字符串类型\n",
    "response_to_string = response.to_string()\n",
    "print(response_to_string)\n",
    "print(type(response_to_string))"
   ],
   "id": "987489776204852e",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[SystemMessage(content='你是一个AI助手，你的名字叫小智', additional_kwargs={}, response_metadata={}), HumanMessage(content='我的问题是1 + 2 * 3 = ？', additional_kwargs={}, response_metadata={})]\n",
      "<class 'list'>\n",
      "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n",
      "System: 你是一个AI助手，你的名字叫小智\n",
      "Human: 我的问题是1 + 2 * 3 = ？\n",
      "<class 'str'>\n"
     ]
    }
   ],
   "execution_count": 12
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## 3、更丰富的实例化参数类型\n",
    "\n",
    "本质：不管使用构造方法、还是使用from_message()来创建ChatPromptTemplate的实例，本质上来讲，传入的都是消息构成的列表。\n",
    "\n",
    "从调用上来讲，我们看到，不管使用构造方法，还是使用from_message()，messages参数的类型都是列表，但是列表的元素的类型是多样的。元素可以是：\n",
    "\n",
    "字符串类型、字典类型、消息类型、元组构成的列表（最常用、最基础、最简单）、Chat提示词模板类型、消息提示词模板类型\n",
    "\n",
    "举例1：元组构成的列表（最常用、最基础、最简单）"
   ],
   "id": "97db37ce4fda316b"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T17:45:59.699167Z",
     "start_time": "2025-09-28T17:45:59.692742Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "\n",
    "# 创建实例\n",
    "#第1种方式\n",
    "chat_prompt_template1 = ChatPromptTemplate(\n",
    "    messages=[\n",
    "        (\"system\", \"你是一个AI助手，你的名字叫{name}\"),\n",
    "        (\"human\", \"我的问题是{question}\")\n",
    "    ]\n",
    ")\n",
    "#第2种方式\n",
    "chat_prompt_template2 = ChatPromptTemplate.from_messages([\n",
    "    (\"system\", \"你是一个AI助手，你的名字叫{name}\"),\n",
    "    (\"human\", \"我的问题是{question}\")\n",
    "])\n",
    "\n",
    "#\n",
    "response = chat_prompt_template1.invoke({\"name\": \"小智\", \"question\": \"1 + 2 * 3 = ？\"})"
   ],
   "id": "ccb55ebb569a975d",
   "outputs": [],
   "execution_count": 13
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：字符串",
   "id": "d7a144d700e1a91e"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T17:47:34.129236Z",
     "start_time": "2025-09-28T17:47:34.122840Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "\n",
    "# 创建实例\n",
    "chat_prompt_template = ChatPromptTemplate.from_messages([\n",
    "    \"我的问题是{question}\"  #默认的角色是：human !\n",
    "])\n",
    "\n",
    "#\n",
    "response = chat_prompt_template.invoke({\"question\": \"1 + 2 * 3 = ？\"})\n",
    "print(response)"
   ],
   "id": "1c979d0455ac87e5",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "messages=[HumanMessage(content='我的问题是1 + 2 * 3 = ？', additional_kwargs={}, response_metadata={})]\n"
     ]
    }
   ],
   "execution_count": 14
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例3：字典类型",
   "id": "4435c63082c9a28d"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T17:48:21.558330Z",
     "start_time": "2025-09-28T17:48:21.548703Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "\n",
    "# 创建实例\n",
    "chat_prompt_template = ChatPromptTemplate.from_messages([\n",
    "    {\"role\": \"system\", \"content\": \"我是一个人工智能助手，我的名字叫{name}\"},\n",
    "    {\"role\": \"human\", \"content\": \"我的问题是{question}\"},\n",
    "])\n",
    "\n",
    "#\n",
    "response = chat_prompt_template.invoke({\"name\": \"小智\", \"question\": \"1 + 2 * 3 = ？\"})\n",
    "print(response)"
   ],
   "id": "54507b02590a60a0",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "messages=[SystemMessage(content='我是一个人工智能助手，我的名字叫小智', additional_kwargs={}, response_metadata={}), HumanMessage(content='我的问题是1 + 2 * 3 = ？', additional_kwargs={}, response_metadata={})]\n"
     ]
    }
   ],
   "execution_count": 15
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例4：消息类型",
   "id": "8795d619f89d0cfc"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T17:49:04.393977Z",
     "start_time": "2025-09-28T17:49:04.385480Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain_core.messages import SystemMessage, HumanMessage\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "\n",
    "# 创建实例\n",
    "chat_prompt_template = ChatPromptTemplate.from_messages([\n",
    "    SystemMessage(content=\"我是一个人工智能助手，我的名字叫{name}\"),\n",
    "    HumanMessage(content=\"我的问题是{question}\")\n",
    "])\n",
    "\n",
    "#\n",
    "# response = chat_prompt_template.invoke({\"name\":\"小智\", \"question\":\"1 + 2 * 3 = ？\"})\n",
    "response = chat_prompt_template.invoke({})\n",
    "print(response)"
   ],
   "id": "69da823d676f767",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "messages=[SystemMessage(content='我是一个人工智能助手，我的名字叫{name}', additional_kwargs={}, response_metadata={}), HumanMessage(content='我的问题是{question}', additional_kwargs={}, response_metadata={})]\n"
     ]
    }
   ],
   "execution_count": 16
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例5：Chat提示词模板类型",
   "id": "aa05637c0c6da895"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T17:50:14.926487Z",
     "start_time": "2025-09-28T17:50:14.913079Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "\n",
    "# 使用 BaseChatPromptTemplate（嵌套的 ChatPromptTemplate）\n",
    "nested_prompt_template1 = ChatPromptTemplate.from_messages([\n",
    "    (\"system\", \"我是一个人工智能助手，我的名字叫{name}\")\n",
    "])\n",
    "nested_prompt_template2 = ChatPromptTemplate.from_messages([\n",
    "    (\"human\", \"很高兴认识你,我的问题是{question}\")\n",
    "])\n",
    "\n",
    "prompt_template = ChatPromptTemplate.from_messages([\n",
    "    nested_prompt_template1,\n",
    "    nested_prompt_template2\n",
    "])\n",
    "\n",
    "prompt_template.format_messages(name=\"小智\", question=\"你为什么这么帅？\")"
   ],
   "id": "993c143f26271f74",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[SystemMessage(content='我是一个人工智能助手，我的名字叫小智', additional_kwargs={}, response_metadata={}),\n",
       " HumanMessage(content='很高兴认识你,我的问题是你为什么这么帅？', additional_kwargs={}, response_metadata={})]"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 17
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例6：消息提示词模板类型",
   "id": "57da400208893f9c"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T17:56:58.645017Z",
     "start_time": "2025-09-28T17:56:58.626520Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.prompts import SystemMessagePromptTemplate, HumanMessagePromptTemplate\n",
    "\n",
    "# 创建消息模板\n",
    "system_template = \"你是一个专家{role}\"\n",
    "system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)\n",
    "\n",
    "human_template = \"给我解释{concept}，用浅显易懂的语言\"\n",
    "human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)\n",
    "\n",
    "# 组合成聊天提示模板\n",
    "chat_prompt = ChatPromptTemplate.from_messages([\n",
    "    system_message_prompt, human_message_prompt\n",
    "])\n",
    "\n",
    "# 格式化提示\n",
    "formatted_messages = chat_prompt.format_messages(role=\"物理学家\", concept=\"相对论\")\n",
    "\n",
    "print(formatted_messages)"
   ],
   "id": "ef257bed054d4e2a",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[SystemMessage(content='你是一个专家物理学家', additional_kwargs={}, response_metadata={}), HumanMessage(content='给我解释相对论，用浅显易懂的语言', additional_kwargs={}, response_metadata={})]\n"
     ]
    }
   ],
   "execution_count": 19
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 4、结合LLM",
   "id": "11a7aed09b2cc1d0"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T17:57:47.067966Z",
     "start_time": "2025-09-28T17:57:43.534077Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "# 1、提供大模型\n",
    "from langchain_openai import ChatOpenAI\n",
    "import os\n",
    "import dotenv\n",
    "\n",
    "#加载配置文件\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "os.environ[\"OPENAI_BASE_URL\"] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY1\")\n",
    "\n",
    "# 获取对话模型：\n",
    "chat_model = ChatOpenAI(\n",
    "    model=\"gpt-4o-mini\"\n",
    ")\n",
    "\n",
    "# 2、通过Chat提示词模板，创建提示词\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "\n",
    "# 创建实例\n",
    "chat_prompt_template = ChatPromptTemplate.from_messages([\n",
    "    (\"system\", \"你是一个AI助手，你的名字叫{name}\"),\n",
    "    (\"human\", \"我的问题是{question}\")\n",
    "])\n",
    "\n",
    "prompt_response = chat_prompt_template.invoke({\"name\": \"小智\", \"question\": \"1 + 2 * 3 = ？\"})\n",
    "\n",
    "# 3、通过大模型调用提示词，得到响应数据\n",
    "response = chat_model.invoke(prompt_response)\n",
    "print(response)"
   ],
   "id": "7b9ab3d9af844bf7",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "content='根据数学运算的优先级，先进行乘法运算，然后进行加法运算。\\n\\n1 + 2 * 3 = 1 + 6 = 7\\n\\n所以，1 + 2 * 3 = 7。' additional_kwargs={'refusal': None} response_metadata={'token_usage': {'completion_tokens': 53, 'prompt_tokens': 35, 'total_tokens': 88, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_efad92c60b', 'id': 'chatcmpl-CKpwYACANgZl36WqWGVGAIMTlEzCB', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None} id='run--733734fa-be7d-4082-b407-45ac8d41ccc5-0' usage_metadata={'input_tokens': 35, 'output_tokens': 53, 'total_tokens': 88, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}}\n"
     ]
    }
   ],
   "execution_count": 20
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## 5、插入消息列表：MessagePlaceholder\n",
    "\n",
    "使用场景：当ChatPromptTemplatem模板中的消息类型和个数不确定的时候，我们就可以使用MessagePlaceholder。\n",
    "\n",
    "举例1："
   ],
   "id": "6d152e364c0ba63"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T18:03:20.016504Z",
     "start_time": "2025-09-28T18:03:20.006515Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "from langchain_core.prompts.chat import MessagesPlaceholder\n",
    "\n",
    "chat_prompt_template = ChatPromptTemplate.from_messages([\n",
    "    (\"system\", \"你是一个AI助手，你的名字叫{name}\"),\n",
    "    MessagesPlaceholder(variable_name=\"msgs\")\n",
    "]\n",
    ")\n",
    "\n",
    "chat_prompt_template.invoke({\n",
    "    \"name\": \"小智\",\n",
    "    \"msgs\":[HumanMessage(content=\"我的问题是：1 + 2 * 3 = ?\")]\n",
    "})"
   ],
   "id": "b1b05c7f54d1a8c8",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ChatPromptValue(messages=[SystemMessage(content='你是一个AI助手，你的名字叫小智', additional_kwargs={}, response_metadata={}), HumanMessage(content='我的问题是：1 + 2 * 3 = ?', additional_kwargs={}, response_metadata={})])"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 23
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：",
   "id": "52496723e7e5e7f2"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T18:03:51.185240Z",
     "start_time": "2025-09-28T18:03:51.175463Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain_core.messages import AIMessage\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "from langchain_core.prompts.chat import MessagesPlaceholder\n",
    "\n",
    "chat_prompt_template = ChatPromptTemplate.from_messages([\n",
    "    (\"system\", \"你是一个AI助手，你的名字叫{name}\"),\n",
    "    MessagesPlaceholder(variable_name=\"msgs\")\n",
    "])\n",
    "\n",
    "chat_prompt_template.invoke({\n",
    "    \"name\": \"小智\",\n",
    "    \"msgs\": [HumanMessage(content=\"我的问题是：1 + 2 * 3 = ?\"),AIMessage(content=\"1 + 2 * 3 = 7\")]\n",
    "})"
   ],
   "id": "b8c0eb455d3bd5d4",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ChatPromptValue(messages=[SystemMessage(content='你是一个AI助手，你的名字叫小智', additional_kwargs={}, response_metadata={}), HumanMessage(content='我的问题是：1 + 2 * 3 = ?', additional_kwargs={}, response_metadata={}), AIMessage(content='1 + 2 * 3 = 7', additional_kwargs={}, response_metadata={})])"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 24
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例3：存储对话历史记录",
   "id": "552bb0a2ef092e54"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T18:04:50.148451Z",
     "start_time": "2025-09-28T18:04:50.140703Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
    "from langchain_core.messages import AIMessage\n",
    "\n",
    "prompt = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\"system\", \"You are a helpful assistant.\"),\n",
    "        MessagesPlaceholder(\"history\"),\n",
    "        (\"human\", \"{question}\")\n",
    "    ]\n",
    ")\n",
    "\n",
    "prompt_value = prompt.format_messages(\n",
    "    history=[HumanMessage(content=\"1+2*3 = ?\"),AIMessage(content=\"1+2*3=7\")],\n",
    "    question=\"我刚才问题是什么？\")\n",
    "\n",
    "print(prompt_value)\n",
    "\n",
    "# prompt.invoke(\n",
    "#     {\n",
    "#         \"history\": [(\"human\", \"what's 5 + 2\"), (\"ai\", \"5 + 2 is 7\")],\n",
    "#         \"question\": \"now multiply that by 4\"\n",
    "#     }\n",
    "# )"
   ],
   "id": "f7f6014463966bf6",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[SystemMessage(content='You are a helpful assistant.', additional_kwargs={}, response_metadata={}), HumanMessage(content='1+2*3 = ?', additional_kwargs={}, response_metadata={}), AIMessage(content='1+2*3=7', additional_kwargs={}, response_metadata={}), HumanMessage(content='我刚才问题是什么？', additional_kwargs={}, response_metadata={})]\n"
     ]
    }
   ],
   "execution_count": 25
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T18:05:17.388324Z",
     "start_time": "2025-09-28T18:05:16.020015Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "\n",
    "from langchain_openai import ChatOpenAI\n",
    "import os\n",
    "import dotenv\n",
    "\n",
    "#加载配置文件\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "os.environ[\"OPENAI_BASE_URL\"] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY1\")\n",
    "\n",
    "# 获取对话模型：\n",
    "chat_model = ChatOpenAI(\n",
    "    model=\"gpt-4o-mini\"\n",
    ")\n",
    "\n",
    "chat_model.invoke(prompt_value)"
   ],
   "id": "b47e4f8e9a5c15de",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='你刚才的问题是“1+2*3=？”。', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 15, 'prompt_tokens': 45, 'total_tokens': 60, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_efad92c60b', 'id': 'chatcmpl-CKq3pAN4b52hjiWAfb91W9dYRm7zM', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None}, id='run--24b31f27-80e9-4eef-a12f-21b94379075d-0', usage_metadata={'input_tokens': 45, 'output_tokens': 15, 'total_tokens': 60, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 26
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
